<h1>接收消息</h1>
<div id="message">
	
</div>

用户id:<input id="uid" /><br />
用户名:<input id="uname" /><br />
敌方用户id:<input id="toUid" /><br />
消息类型:<input id="type" value="1" />

<h1>发送消息</h1>
<textarea id="sendMessage"></textarea><br />

<input type="button" value="发送" onclick="sendMessage()">

<script type="text/javascript">
var websocket = {
	sock: null,
	 
	    onOpen: function () {
	        console.log("连接成功");
	    },
	    
	    onMessage: function (event) {
	        console.log("接收消息:" + event.data);
	    },
	 
	    onClose: function () {
	    	console.log("关闭连接");
	        this.close();
	    },
	 
	    onError: function () {
	    	console.log("发生错误");
	        this.close();
	    },
	    
	    close: function () {
	        if(this.sock){
	            this.sock.close();
	            this.sock = null;
	        }
	    },
	 
	    connect: function (url) {
	        this.sock = new WebSocket(url);
	        this.sock.binaryType = "arraybuffer";
	        this.sock.onopen = this.onOpen.bind(this);
	        this.sock.onmessage = this.onMessage.bind(this);
	        this.sock.onclose = this.onClose.bind(this);
	        this.sock.onerror = this.onError.bind(this);
	        return this;
	    },
	 
	    sendData: function (data) {
	    	console.log("发送消息:"+data);

	        this.sock.send(data);
	    }
}
</script>
<script type="text/javascript">
var uid,uname;
var websocket;

initUser();
initWebSocket();

function $(id){
	return document.getElementById(id);
}

function onMessage(result){
	console.log("接收消息:" + result.data);
	$('message').innerHTML = result.data;
}

function initUser(){
	uid = Math.ceil(Math.random()*900000)+100000;
	uname = "用户"+uid;
	$('uid').value=uid;
	$('uname').value=uname;
}

function initWebSocket(){
	socket = websocket.connect("ws://localhost:8001/kstarwarApi/game/"+uid+"/"+uname);
	socket.sock.onmessage = onMessage.bind(socket);
}

function sendMessage(){
	var content = $('sendMessage').value;

	var message = {
		user:{
			uid:$('uid').value,
			uname:$('uname').value,
			// victory:0,
			// isGaming:false,
			// isRequesting:false,
		},
		toUid:$('toUid').value,
		type:$('type').value,
		//请求:1-我方请求战斗,2-我方接受战斗,3-我方拒绝战斗,4-我方准备完成,5-我方游戏结束
		//请求:11-我方发射炮弹,12-我方答题正确,13-我方答题错误
		//请求:66-修改用户名
		//请求:88-我方胜利结束战斗,89-我方失败结束战斗,90-我方平局结束战斗
		
		//接收:1-敌方请求战斗,2-敌方接受战斗,3-敌方拒绝战斗,4-敌方准备完成
		//接收:11-敌方发射炮弹,12-敌方答题正确,13-敌方答题错误
		//接收:21-我方题目
		//请求:88-敌方胜利结束战斗,89-敌方失败结束战斗,90-我方平局结束战斗
		//接收:99-敌方掉线
		content:content
	}

	socket.sendData(JSON.stringify(message));
}
</script>